#!/bin/sh

. /etc/utils.sh

fssize()
{
  local size
  size=$(df -k $1 | grep / | sed -e 's/  */ /' | cut -f 2 -d ' ')
  size=$(($size + 0))
  echo $size
}

aux_file=/tmp/gpio/aux1_temperature

case "$1" in
  start)
    mkdir -p /tmp/cwmp/monitoring/dejittering
    mkdir -p /tmp/cwmp/monitoring/epg
    mkdir -p /tmp/cwmp/monitoring/hdmi
    mkdir -p /tmp/cwmp/monitoring/tcp
    mkdir -p /tmp/cwmp/monitoring/ts
    mkdir -p /tmp/acs
    mkdir -p /tmp/wifi/wifiinfo
    chmod 777 /tmp/cwmp/monitoring /tmp/cwmp/monitoring/* /tmp/acs

    if interface_exists quantenna; then
      touch "$aux_file"
    fi

    if is-storage-box; then
      swimage=/var/media/swimage
    elif [ "$(fssize /user)" -ge 1000000 ]; then
      swimage=/user/swimage
    else
      swimage=/tmp/swimage
    fi
    mkdir -p $swimage
    rm -f $swimage/*.gi
    rm -rf $swimage/dnld
    nice babysit 60 cwmp_monitor | logos cwmp_monitor &

    if runnable moca2json; then
      [ -e /sys/class/net/eth1 ] && iface=eth1
      [ -e /sys/class/net/moca0 ] && iface=moca0
      dir=/tmp/cwmp/monitoring/moca2
      mkdir -p "$dir"
      if [ -n "$iface" ]; then
        nice babysit 60 moca2json -i "$iface" -d "$dir" 2>&1 | logos moca2json &
      fi
    fi

    if is-network-box || is-storage-box || is-tv-box; then
      DIAGUI="--diagui"
      TECHUI="--techui"
    fi
    LICENSEUI="--licenseui"

    if [ -e /tmp/factory_status ]; then
      FACTORY="--factory"
    fi
    umask 022

    # With default CWMPRetryIntervalMultiplier, CWMP
    # maximum exponential backoff is 5120 seconds.
    # Set the alivemonitor to somewhat longer than that.
    supernice babysit 60 \
      alivemonitor /tmp/cwmp/acscontact 300 180 7200 \
      cwmpd $DIAGUI $TECHUI $LICENSEUI $FACTORY 2>&1 | logos cwmpd 0 20000000 &

    if is-network-box || is-storage-box; then
      poll_hostnames | logos hostnames &
    fi
    ;;
  stop)
    pkillwait -f '^python /usr/catawampus/cwmpd'
    pkillwait -f '^alivemonitor.*cwmpd'
    pkillwait -x cwmp_monitor
    pkillwait -x isostream
    pkillwait -x poll_hostnames
    pkillwait -x moca2json
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
